/* eslint-disable prettier/prettier */
<template>
  <el-container>
    <!-- 左边区域 -->
    <el-main>
      <template v-if="!if_tPeople">
        <div class="top">
          <el-input v-model="seName" style="width: 250px;font-size: 17px;height: 30px;" placeholder="搜索计划表名称"
            :prefix-icon="Search" />
          <el-radio-group v-model="radio" style="margin-left: 60px;">
            <el-radio :value="3">显示全部</el-radio>
            <el-radio :value="6">已执行</el-radio>
            <el-radio :value="9">未执行</el-radio>
          </el-radio-group>
        </div>
        <table class="content">
          <thead>
            <tr>
              <td><input type="checkbox" v-model="isAllSelected" @change="toggleAll"></td>
              <td>名称</td>
              <td>开始时间</td>
              <td>结束时间</td>
              <td>状态</td>
              <td>操作</td>
            </tr>
          </thead>
          <tbody>
            <!-- 循环渲染计划信息 -->
            <tr v-for="(planInfo, index) in filteredPlanInfos" :key="planInfo.id"
              :style="{ backgroundColor: planInfo.status ? '' : 'rgba(245, 207, 195)' }">
              <template v-if="index >= pageSize * currentPage - pageSize && index < pageSize * currentPage">
                <td>
                  <input type="checkbox" v-model="selectedIds" :value="planInfo.id" @change="checkAllStatus">
                </td>
                <td>{{ planInfo.name }}</td>
                <td>{{ planInfo.startDate }}</td>
                <td>{{ planInfo.endDate }}</td>
                <td>{{ planInfo.status ? '已执行' : '未执行' }}</td>
                <td>
                  <el-button @click="seeDetail(planInfo.id)" type="success" :icon="View" circle
                    style="background-color: rgb(102, 159, 98);" />
                  <el-button @click="edit(planInfo.id)" type="success" :icon="EditPen" circle
                    style="background-color: rgb(102, 159, 98);" />
                </td>
              </template>
            </tr>
          </tbody>

        </table>
        <!-- 分页 -->
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[3, 7, 12, 30]"
          :size="size1" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
          :total="planTotal" pager-count="4" default-page-size="12" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" style="float: right;" />

      </template>

      <!-- 人员表 -->
      <div v-if="if_tPeople">
        <button @click="back" class="btn-Back" style="margin-bottom: 10px;">
          <el-icon>
            <ArrowLeftBold />
          </el-icon>
        </button>
        <el-table :data="currentPeoples" height="450" style="width: 100%;margin-bottom: 10px;">
          <el-table-column prop="id" label="编号" width="150" />
          <el-table-column prop="name" label="姓名" width="180" />
          <el-table-column prop="department" label="部门" width="180" />
          <el-table-column prop="position" label="职位" width="180" />

          <el-table-column width="100" v-if="!isAbled">
            <template v-slot="{ row }">
              <el-popconfirm title="确定删除吗？" @confirm="delPeople(row.id)">
                <template #reference>
                  <el-button type="danger" :icon="Delete" circle />
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <div v-if="!isAbled" class="people-add">
          <span>选择添加人员: </span>
          <el-cascader :options="options" v-model="addPeopleInfo" :show-all-levels="false" style="width: 380px;" />
          <el-button :icon="Plus" circle @click="addPeople" style="margin-left: 10px;" type="primary" />
        </div>

      </div>
    </el-main>
    <!-- 右边区域 -->
    <el-aside style="width: 35%;">
      <!-- 功能按钮 -->
      <button @click="add" class="btn" v-if="!isForm">添 加</button><br>
      <button @click="del" class="btn" v-if="!isForm">删 除 </button><br>

      <!-- 表单 -->
      <div v-if="isForm" class="formInfo">
        <!-- 关闭图标 -->
        <button @click="closeHandle" class="btnClose"><el-icon>
            <Close />
          </el-icon></button>

        <el-form :model="form" label-width="auto" style="max-width: 600px">
          <el-form-item label="计划表名称">
            <el-input v-model="form.name" :disabled="isAbled" />
          </el-form-item>

          <el-form-item label="具体内容">
            <el-input v-model="form.detail" type="textarea" rows="5" :disabled="isAbled" />
          </el-form-item>

          <el-form-item label="开始时间">
            <el-date-picker v-model="form.startDate" type="date" placeholder="选择开始日期" :size="size"
              :disabled="isAbled" />
          </el-form-item>
          <el-form-item label="结束时间">
            <el-date-picker v-model="form.endDate" type="date" placeholder="选择结束日期" :size="size" :disabled="isAbled" />
          </el-form-item>

          <el-form-item label="总天数">
            <el-input v-model="form.days" :disabled="isAbled" />
          </el-form-item>

          <el-form-item label="参与人员">
            <el-button @click="seePeoples(form.id)" v-model="form.employeeCompanies">查看</el-button>
          </el-form-item>

          <el-form-item label="是否执行">
            <el-input v-model="form.status" :disabled="isAbled" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="save" style="margin-left: 200px;" v-if="!isAbled">保存</el-button>
          </el-form-item>
        </el-form>
      </div>

    </el-aside>
  </el-container>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { Close, Search, EditPen, View, ArrowLeftBold, Delete, Plus } from '@element-plus/icons-vue'
import type { ComponentSize } from 'element-plus'
import { useProfessionalStore } from '@/stores/modules/professional.js'   // 导入

// 获取数据
const professionalStore = useProfessionalStore()   // 调用store实例
const planInfos = ref([])  // 总数据
const dpes = ref({}) // 获取部门职位员工信息
const planTotal = ref(0)  // 数量
// 进入页面时加载的数据
onMounted(async () => {
  await professionalStore.fetchTrainingProgramsAll()
  await professionalStore.fetchDPEs()
  // 赋值
  planInfos.value = professionalStore.trainingPrograms.scheme
  planTotal.value = professionalStore.trainingPrograms.total
  dpes.value = professionalStore.dpes.employee

})

// 搜索过滤
const seName = ref('')  // 存储搜索信息
const radio = ref(3)  // 单选区
// 信息过滤
const filteredPlanInfos = computed(() => {
  let filtered = [...planInfos.value]; // 创建planInfos.value的副本，避免直接修改原始数据

  // 过滤名称
  if (seName.value) {
    filtered = filtered.filter(item => item.name.toLowerCase().includes(seName.value.toLowerCase()));
    
  }

  // 根据radio.value的值过滤状态
  if (radio.value === 3) {
    // 不过滤状态
  } else if (radio.value === 6) {
    filtered = filtered.filter(plan => plan.status);
  } else if (radio.value === 9) {
    filtered = filtered.filter(plan => !plan.status);
  }

  planTotal.value = filtered.length  // 更新总数
  return filtered;
});

// 全选
const isAllSelected = ref(false)  // 控制是否全选
const selectedIds = ref([])  // 控制选择的id数组
const toggleAll = () => {
  // 当全选checkbox状态改变时，更新所有子checkbox的状态
  selectedIds.value = isAllSelected.value ? filteredPlanInfos.value.map(item => item.id) : []
}
const checkAllStatus = () => {
  // 当任何子checkbox状态改变时，检查是否所有子checkbox都被选中
  isAllSelected.value = filteredPlanInfos.value.length === selectedIds.value.length
}

// 表单信息
const isForm = ref(false)  // 控制表单的显示
const form = ref({  // 存储表单信息
  id: 0,
  name: '',
  detail: '',
  startDate: '',
  endDate: '',
  days: 1,
  employeeCompanies: [],
  status: ''
})

// 查看详情
const seeDetail = async (id) => {
  isAbled.value = true  // 不可编辑
  isForm.value = true  // 显示表单
  console.log('id', id)
  // 赋值
  const data = await professionalStore.trainingDetail(id)
  form.value = data
  currentPeoples.value = form.value.employeeCompanies
  form.value.status = form.value.status ? '是' : '否'   // 修改状态显示
}
// 编辑
const edit = async (id) => {
  isAbled.value = false  // 可编辑
  isForm.value = true  // 显示表单
  // 赋值
  const data = await professionalStore.trainingDetail(id)
  form.value = data
  currentPeoples.value = form.value.employeeCompanies
  form.value.status = form.value.status ? '是' : '否'   // 修改状态显示

}

const currentPeoples = ref([])  // 存储当前数据的人员信息
// 查看人员
const if_tPeople = ref(false)   // 控制人员表的显示
const isAbled = ref(false)      // 控制表单是否禁用
const seePeoples = (id) => {
  if_tPeople.value = true  // 显示人员表
}
// 返回
const back = () => {
  if_tPeople.value = false
}

// 添加人员
const props = {
  multiple: true,
  checkStrictly: true,
}
const options = computed(() => {   // 赋值选择器值
  return Object.keys(dpes.value).map(department => ({
    value: department,
    label: department,
    children: Object.keys(dpes.value[department]).map(position => ({
      value: position,
      label: position,
      children: dpes.value[department][position].map(employee => ({
        value: `${employee.id}-${employee.name}`,
        label: employee.name
      }))
    }))
  }));
});
const addPeopleInfo = ref('')  // 级联选择器的信息
const addPeople = () => {
  console.log('选出的人员信息', addPeopleInfo.value)
  if (addPeopleInfo.value) {
    const parts = addPeopleInfo.value[2].split("-");
    const id = parts[0]
    const name = parts[1]
    const data = ref({
      "id": id,
      "name": name,
      "department": addPeopleInfo.value[0],
      "position": addPeopleInfo.value[1],
      "status": 1
    })
    currentPeoples.value.push(data.value)
  }

  addPeopleInfo.value = '' // 清空选项
}
// 删除人员
const delPeople = (id) => {
  console.log('row-id', id)
  for (var i = 0; i < currentPeoples.value.length; i++) {
    if (currentPeoples.value[i].id == id) {
      currentPeoples.value.splice(i, 1)
      console.log('删除后currentPeoples', currentPeoples.value)
      break;
    }
  }
}

// ×关闭表单
const closeHandle = () => {
  isForm.value = false
}
// 时间选择
const size = ref<'default' | 'large' | 'small'>('default')
// 日期格式转换
const formatDate = (date) => {
  // 判断输入是否为字符串，如果是则直接返回
  if (typeof date === 'string') {
    return date;
  }
  var year = date.getFullYear();
  var month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份是从0开始的，所以要加1，并确保是两位数
  var day = date.getDate().toString().padStart(2, '0'); // 确保日期是两位数
  return `${year}-${month}-${day}`;
}

//添加
const add = () => {
  isAbled.value = false  // 可编辑
  isForm.value = true  // 显示表单
  //清空
  form.value.id = null,
    form.value.name = '',
    form.value.detail = '',
    form.value.startDate = '',
    form.value.endDate = '',
    form.value.days = null,
    form.value.employeeCompanies = [],
    currentPeoples.value = [],
    form.value.status = ''
}

// 保存
const save = async () => {
  console.log('submit!')
  if (form.value.id) { // 编辑
    const data = ref({
      id: form.value.id,
      name: form.value.name,
      detail: form.value.detail,
      startDate: formatDate(form.value.startDate),
      endDate: formatDate(form.value.endDate),
      ee: [],
      status: form.value.status === '是' ? 1 : 0
    })
    // 使用forEach循环遍历currentPeoples.value数组，并将每个员工的ID推入eIds数组
    currentPeoples.value.forEach((people) => {
      data.value.ee.push(people.id);
    });
    console.log('已经处理号的data', data.value)
    await professionalStore.editTraining(data)  // 等待执行
    planInfos.value = professionalStore.trainingPrograms.scheme  //重新赋值
    planTotal.value = professionalStore.trainingPrograms.total

  } else { // 添加
    const data = ref({
      id: 0,
      name: form.value.name,
      detail: form.value.detail,
      startDate: formatDate(form.value.startDate),
      endDate: formatDate(form.value.endDate),
      days: form.value.days,
      ee: [],
      status: form.value.status === '是' ? 1 : 0
    })

    data.value.id = planInfos.value[planInfos.value.length - 1].id + 1
    console.log('newId', data.value.id)
    currentPeoples.value.forEach((people) => {
      data.value.ee.push(people.id);
    });

    await professionalStore.addTraining(data)  // 等待添加执行
    planInfos.value = professionalStore.trainingPrograms.scheme  //重新赋值
    planTotal.value = professionalStore.trainingPrograms.total
  }

  if_tPeople.value = false // 关闭人员表
  isForm.value = false // 关闭
}

// 删除选中
const del = async () => {
  const del = async () => {
  // 使用filter方法移除选中的项
  // planInfos.value = planInfos.value.filter(item => !selectedIds.value.includes(item.id));
  console.log('selectedIds', selectedIds.value)

  // const normalArray = Array.from(selectedIds.value);
  if (selectedIds.value.length) {
    await professionalStore.delTraining(selectedIds.value)  // 等待执行
    planInfos.value = professionalStore.trainingPrograms.scheme  //重新赋值
    planTotal.value = professionalStore.trainingPrograms.total

    selectedIds.value = []; // 清空选中状态
  }

}
}

// 分页
const currentPage = ref(1)
const pageSize = ref(8)
const size1 = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
}

</script>

<style scoped>
/* 信息表格 */
.content {
  width: 100%;
  margin-bottom: 15px;
  border-collapse: separate;
  /* 设置边框分离，以便单独控制每个单元格的边框 */
  border-spacing: 0;
  /* 移除单元格之间的间距 */
}

.top {
  white-space: nowrap;
  margin-bottom: 15px;
}

.content thead {
  font-size: 18px;
  font-weight: 600;
  background-color: rgb(102, 159, 98);
}

.content td,
.content th {
  border-bottom: 2px dashed rgb(189, 233, 213);
  /* 仅为单元格的底部添加边框 */
  padding: 8px;
}

.content tbody tr:hover {
  background-color: rgb(250, 149, 121);
  /* 鼠标悬停时的背景颜色 */
}


/* 表单 */
.btnClose {
  margin-left: 400px;
  margin-bottom: 10px;
  background-color: transparent;
  border: none;
  font-size: 18px
}

.btnClose:hover {
  background-color: #e4e0e0;
}

.tp {
  width: 100%;
  font-size: 17px;
}

.people-add {
  white-space: nowrap;
}

/* 人员信息  */
.btn-Back {
  font-size: 20px;
  border: none;
  background-color: transparent;
  height: 20px;
  border-radius: 0.5em;
}

.btn-Back:hover {
  background-color: rgb(229, 225, 225);
}

/*功能按钮 */
.btn {
  margin-top: 140px;
  margin-left: 50px;
  width: 100px;
  height: 40px;
  font-size: 18px;
  border-radius: 0.5em;
  border: none;
  background-color: rgb(127, 170, 231);
  color: white;
}

.btn:hover {
  background-color: rgb(90, 142, 215);
}
</style>